import { Context } from 'koa';
import { query, queryOne } from '../database/mysql';
import { Category } from '../database/models';
import { utils } from '../utils/utils';
import { success, error } from '../utils/response';
import { ResponseCode } from '../config/responseCode';

/**
 * 创建分类
 */
export async function createCategory(ctx: Context): Promise<void> {
  const { name, description, sort_order } = ctx.request.body as {
    name?: string;
    description?: string;
    sort_order?: number;
  };

  if (!name) {
    error(ctx, ResponseCode.BAD_REQUEST, '分类名称不能为空');
    return;
  }

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  // 检查分类是否已存在（同一用户下）
  const existingCategory = await queryOne<Category>(
    'SELECT * FROM categories WHERE user_id = ? AND name = ?',
    [userId, name]
  );

  if (existingCategory) {
    error(ctx, ResponseCode.BAD_REQUEST, '分类名称已存在');
    return;
  }

  // 创建分类
  const categoryId = utils.generateUUID();
  await query(
    `INSERT INTO categories (id, user_id, name, description, sort_order)
     VALUES (?, ?, ?, ?, ?)`,
    [categoryId, userId, name, description || null, sort_order || 0]
  );

  const newCategory = await queryOne<Category>('SELECT * FROM categories WHERE id = ?', [categoryId]);
  success(ctx, newCategory);
}

/**
 * 更新分类
 */
export async function updateCategory(ctx: Context): Promise<void> {
  const { id, name, description, sort_order } = ctx.request.body as {
    id?: string;
    name?: string;
    description?: string;
    sort_order?: number;
  };

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '分类ID不能为空');
    return;
  }

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  // 检查分类是否存在且属于当前用户
  const category = await queryOne<Category>('SELECT * FROM categories WHERE id = ? AND user_id = ?', [id, userId]);
  if (!category) {
    error(ctx, ResponseCode.BAD_REQUEST, '分类不存在');
    return;
  }

  // 如果更新名称，检查新名称是否已存在
  if (name && name !== category.name) {
    const existingCategory = await queryOne<Category>(
      'SELECT * FROM categories WHERE user_id = ? AND name = ? AND id != ?',
      [userId, name, id]
    );
    if (existingCategory) {
      error(ctx, ResponseCode.BAD_REQUEST, '分类名称已存在');
      return;
    }
  }

  // 更新分类信息
  const updates: string[] = [];
  const params: any[] = [];

  if (name !== undefined) {
    updates.push('name = ?');
    params.push(name);
  }
  if (description !== undefined) {
    updates.push('description = ?');
    params.push(description);
  }
  if (sort_order !== undefined) {
    updates.push('sort_order = ?');
    params.push(sort_order);
  }

  if (updates.length > 0) {
    params.push(id, userId);
    await query(`UPDATE categories SET ${updates.join(', ')} WHERE id = ? AND user_id = ?`, params);
  }

  const updatedCategory = await queryOne<Category>('SELECT * FROM categories WHERE id = ? AND user_id = ?', [id, userId]);
  if (!updatedCategory) {
    error(ctx, ResponseCode.BAD_REQUEST, '分类不存在');
    return;
  }
  success(ctx, updatedCategory);
}

/**
 * 删除分类
 */
export async function deleteCategory(ctx: Context): Promise<void> {
  const { id } = ctx.request.body as { id?: string };

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '分类ID不能为空');
    return;
  }

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  // 检查分类是否存在且属于当前用户
  const category = await queryOne<Category>('SELECT * FROM categories WHERE id = ? AND user_id = ?', [id, userId]);
  if (!category) {
    error(ctx, ResponseCode.BAD_REQUEST, '分类不存在');
    return;
  }

  // 删除分类关联关系
  await query('DELETE FROM blog_relations WHERE relation_type = ? AND relation_id = ?', ['category', id]);

  // 删除分类
  await query('DELETE FROM categories WHERE id = ? AND user_id = ?', [id, userId]);

  success(ctx, { message: '删除成功' });
}

/**
 * 查询分类列表
 */
export async function getCategoryList(ctx: Context): Promise<void> {
  const { page = 1, pageSize = 100, name } = ctx.request.body as {
    page?: number;
    pageSize?: number;
    name?: string;
  };

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  let sql = 'SELECT * FROM categories WHERE user_id = ?';
  const params: any[] = [userId];

  if (name) {
    sql += ' AND name LIKE ?';
    params.push(`%${name}%`);
  }

  sql += ' ORDER BY sort_order ASC, created_at DESC LIMIT ? OFFSET ?';
  const offset = (page - 1) * pageSize;
  params.push(pageSize, offset);

  const categories = await query<Category>(sql, params);

  // 构建总数查询
  let countSql = 'SELECT COUNT(*) as count FROM categories WHERE user_id = ?';
  const countParams: any[] = [userId];
  
  if (name) {
    countSql += ' AND name LIKE ?';
    countParams.push(`%${name}%`);
  }

  const totalResult = await queryOne<{ count: number }>(countSql, countParams);

  success(ctx, {
    list: categories,
    total: totalResult?.count || 0,
    page,
    pageSize,
  });
}

/**
 * 查询分类详情
 */
export async function getCategoryDetail(ctx: Context): Promise<void> {
  const { id } = ctx.request.body as { id?: string };

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '分类ID不能为空');
    return;
  }

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  const category = await queryOne<Category>('SELECT * FROM categories WHERE id = ? AND user_id = ?', [id, userId]);
  if (!category) {
    error(ctx, ResponseCode.BAD_REQUEST, '分类不存在');
    return;
  }

  success(ctx, category);
}

